 // jQuery fn disableTextSelect                                     
$.fn.disableTextSelect = function () {
	return this.each(function () {
    	$(this).css({'-webkit-user-select':'none', '-moz-user-select':'none','user-select':'none'});
	})
};
 // jQuery fn enableTextSelect 
$.fn.enableTextSelect = function () {
	return this.each(function () {
		$(this).css({'-webkit-user-select':'', '-moz-user-select':'','user-select':''});
	})
};

var hasStorage = function () {
  try {
    return 'localStorage' in window && window['localStorage'] !== null;
  } catch (e) {
    return false;
  }
};

// jQuery fn outerHTML
(function($) {
  $.fn.outerHTML = function() {
    return $(this).clone().wrap('<div></div>').parent().html();
  }
})(jQuery);

//douban book article reader
var DoReader = {
	opt : {
		lineNum : 25,//每页高度
		lineHeight : 2,//em
		container : $('#readerbox')
	},
	pn : null,//总页码
	currpn : 1,//当前页码
	currtype : 'v',//当前版式
	currzoom : 's'//当前尺寸
};
//补充方法
DoReader.utils = {
	tmpl:function(sTmpl,opts){
		return sTmpl.replace(/\{\$(\w+)\}/g,function(a,b){return opts[b]});
	},
	escapeHTML: function(str){
	    str = str || '';
	    var xmlchar = {
	        //"&": "&amp;",
	        "<": "&lt;",
	        ">": "&gt;",
	        "'": "&#39;",
	        '"': "&quot;",
	        "{": "&#123;",
	        "}": "&#125;",
	        "@": "&#64;"
	    };
	    return str.replace(/[<>'"\{\}&@]/g, function($1){
	        return xmlchar[$1];
	    });
	},
	autoIframe : function(id){
		var iframe = document.getElementById(id);
		try{
			var bHeight = iframe.contentWindow.document.body.scrollHeight;
			var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
			var height = Math.max(bHeight, dHeight);
			iframe.height =  height;
		}catch (ex){}
	},
	go2page : function(idx){
		$.scrollTo( '#item'+idx, 700);
		$("#sidebar .pager").trigger("updatepager", [idx]);
	},
	go2page2 : function(idx){
		DoReader.opt.container.find('.page-item').css('left','5em');
		var $item = DoReader.opt.container.find('.page-item');
		var idx2 = parseInt(idx) - 1;
		$item.each(function(i){
			if(i < idx2){
				$(this).animate({left:'-40.1em'},600,function() {
					if($(window).scrollTop() !== 0){$.scrollTo( 0, 600);}
				});
			}
		});
		DoReader.currpn = idx;
	},
	uaScreen : function(){
		return {'w':window.screen.width,'h':window.screen.height};
	},
	croplines: function(line_num,line_arr,img_arr){
		console.log(line_arr.toLocaleString() +'###'+img_arr.toLocaleString());
		var lineval = [],
			linekey = [],
			sum = 0,
			pn = 0;	
		for(var i=0,len=line_arr.length,j=0;i<len;i++){
		    sum += line_arr[i];
		    if(sum>line_num){
		        j++;
				var a = sum - line_num,
					b = line_arr[i] - a;
				//需要拆分
				if(line_arr[i] > a){
					if($.inArray(i,img_arr) >= 0){
						sum = line_arr[i];
						lineval.push(b);
						linekey.push(-i);
						lineval.push(line_arr[i]);
						linekey.push(i);
					}else{
						lineval.push(b);
						linekey.push(i);
						if(a>line_num){
							var split = Math.round(a/line_num);
							j += split - 1;
							for(var k = 1;k < split;k++){
								lineval.push(line_num);
								linekey.push(i);
							}
							lineval.push(a - (k-1)*line_num);
							linekey.push(i);
							sum = a - (k-1)*line_num;
						}else{
							lineval.push(a);
							linekey.push(i);
							sum = a;
						}	
					}

				}else{
				//无需拆分
					lineval.push(line_arr[i]);
					linekey.push(i);
					sum = line_arr[i];
				}
		    }else{
				lineval.push(line_arr[i]);
				linekey.push(i);
			}
			pn = j;
		}
		return {
			line_arr: line_arr,
			pn: pn+1,
			linekey: linekey,
			lineval: lineval
		}
	}
};
//渲染文档
DoReader.render = function(cfg){
	//render first page get pagenum
	var config = {callback:function(){},html:''};
	$.extend(config, cfg);

	var that = this,
		_container = that.opt.container,
		_lineHeight = that.opt.lineHeight,
		_lineNum = that.opt.lineNum,
		_fontsize = parseInt(_container.css('fontSize').replace('px',''),10);
	
	//ajax 数据接口
	if(config.html.length){
		_container.html('');
		var _html = [];
		_html.push('<div class="page-item" id="item'+ 1 +'">');
		_html.push('<div class="page-hd"></div><div class="page-bd"><div class="data">'+config.html+'</div></div>');
		_html.push('<div class="page-ft">' + 1 +'</div>');
		_html.push('</div>');
		$(_html.join('')).appendTo(_container);
	}
	
    //get paragraph data
	var paragraph  = [],
		lineH = [],
		lineImg = [];
	_container.find('.line').each(function(i){
		// var pos = {};
		// var par_top = parseInt($(this).position().top,10);
		// // a paragraph has attr margin-bottom eq line-height
		// var par_btm = par_top + parseInt($(this).height());
		// 
		// //the start line
		// pos.start = par_top/(_fontsize * _lineHeight);
		// //the end line
		// pos.end = par_btm/(_fontsize * _lineHeight);
		// pos.isimg = $(this).has('img');
		// pos.ht = parseInt($(this).height())/(_fontsize * _lineHeight);
		// pos.isfloat = $(this).css('float') === 'none' ? false : true;
		// paragraph.push(pos);
		
		var oHeight = parseInt($(this).height())/(_fontsize * _lineHeight),
			oIsImg = $(this).has('img');
		lineH.push(oHeight);
		if(oIsImg.length){
			lineImg.push(i);
		}
	});
	
	//console.log(lineImg);
	
	var lienData = DoReader.utils.croplines(_lineNum,lineH,lineImg);
	DoReader.pn = lienData.pn;
	
	var buildpage = function (line_num,lineval,linekey){
		var lineinpn = [];
		var sum = 0;
		for(var i=0,len=lineval.length,j=0;i<len;i++){
			sum += lineval[i];
			if(sum>line_num){
				j++;
				sum=lineval[i];
			}
			if(lineinpn[j] == undefined){lineinpn[j] = [];}
			//if(linekey[i]>=0){
				(lineinpn[j]).push(i);
			//}
		}
		//return lineinpn;
		console.log(lineinpn);
		var arr_hid = [];
		$.each(lineinpn,function(i){
			var _str = [];
			_str.push('<div class="page-item" id="item'+ (i+1) +'">');
			_str.push('<div class="page-hd"></div><div class="page-bd"><div class="data">');
			
			$.each(lineinpn[i],function(j){

				var key = lineinpn[i][j];
				if(j===0){
					if(linekey[key] == linekey[key-1]){
						arr_hid[key] = lineval[key-1];
					}
				}
				if(linekey[key] >= 0){
					_str.push($(_container.find('.line').get(linekey[key])).outerHTML());
				}else{
					var cssheight = 1.9 * lineval[key];
					_str.push('<p class="line" style="height:'+cssheight+'em;color:#ccc;background:#fafafa;border:1px #eee dashed">----占位符----</p>');	
				}
			});
			
			_str.push('</div></div>');
			_str.push('<div class="page-ft">' + (i+1) + '</div><div class="notation"></div>');
			_str.push('</div>');
			
			$(_str.join('')).appendTo(_container);
		});

		$(_container.find('.page-item').get(0)).remove();
		
		_container.find('.line').each(function(i){
			if(arr_hid[i] != undefined ){
				var mt = arr_hid[i] * _lineHeight;
				$(this).css('margin-top','-'+mt+'em');
			}
		});
	}
	
	buildpage(_lineNum,lienData.lineval,lienData.linekey);
	
	if(DoReader.utils.uaScreen().w > 1024){
		$('#container').get(0).className = 'big';
		$('#zoomtips .ui-size').removeClass('ui-size-on');
		$('#sizebig').addClass('ui-size-on');
		DoReader.currzoom = 'b';
	}

	//callback
	config.callback();
};
//翻页 go2prev go2next go2prev2 go2next2
DoReader.go2prev = function(){
	DoReader.currpn --;
	if(DoReader.currpn > 0){
		var _cssleft = '5em';
		DoReader.opt.container.find('.page-item').eq(DoReader.currpn-1).animate({left:_cssleft},600,function() {
			
			if ($(window).scrollTop() !== 0){
				$.scrollTo( 0, 600);
			}	
		});

	}else{
		DoReader.currpn = 1;
	}
	DoReader.updateToolsPn();
};
DoReader.go2next = function(){
	if(DoReader.currpn < DoReader.pn){
		var _cssleft = '-40.1em';

		DoReader.opt.container.find('.page-item').eq(DoReader.currpn-1).animate({left:_cssleft},600,function() {
			if ($(window).scrollTop() !== 0){
				$.scrollTo( 0, 600);
			}
		});
		DoReader.currpn ++;
	}else{
		DoReader.currpn = DoReader.pn;
	}
	DoReader.updateToolsPn();
};
DoReader.go2prev2 = function(){
	DoReader.currpn --;
	if(DoReader.currpn > 0){
		DoReader.utils.go2page(DoReader.currpn);
	}else{
		DoReader.currpn = 1;
		return;
	}
};
DoReader.go2next2 = function(){
	DoReader.currpn ++;
	if(DoReader.currpn <= DoReader.pn){
		DoReader.utils.go2page(DoReader.currpn);
	}else{
		DoReader.currpn = DoReader.pn;
		return;
	}
};
//更新工具条位置
DoReader.updateTools = function(){
	
	var posX = DoReader.opt.container.offset().left + DoReader.opt.container.outerWidth() + 2,
	$tools = $('#tools');
		
	$tools.css('left',posX+'px');
	var t = DoReader.currtype;
	if(t === 'v'){
		$tools.removeClass('tools-h').addClass('tools-v');
	}else{
		$tools.removeClass('tools-v').addClass('tools-h');
	}
};
//工具条
DoReader.showTools = function(){
	var toolsTemp = $('#db-templ-tools').html();

	if($('#tools').get(0) !=='undefined'){
		$(toolsTemp).appendTo($('#doc'));
	}
	DoReader.updateTools();
	
	if(!$.browser.msie || ($.browser.version !== "6.0")){
		$('#tools').css({'top':'100px','position':'fixed'});
	}
	
	//工具条自动隐藏
	var showTools = function(e) { 
		$(document).unbind('mousemove',showTools);
        $('#tools').stop().animate({ opacity: 1 });
        var _lantency = null,_layTime = 120000;
		clearTimeout(_lantency);
        _lantency = setTimeout(function() {
			$('#tools').stop().animate({ opacity: 0 });
			$(document).bind('mousemove',showTools);
		}, _layTime);
	};
	$(document).bind('mousemove',showTools);
	
	//工具条事件
	$('#tools').find('.info').mouseenter(function(){
		$('#infotext').fadeIn(600);
	}).mouseleave(function(){
		$('#infotext').fadeOut(600);
	})
	.end()
	.find('.keycode').mouseenter(function(){
		$('#keytips').fadeIn(600);
	}).mouseleave(function(){
		$('#keytips').fadeOut(600);
	})
	.end()	
	.find('.up').click(function(e){
		//alert(DoReader.currtype +'###'+DoReader.currpn);
		if (DoReader.currtype === 'v'){
			DoReader.go2prev2();
		}else{
			DoReader.go2prev();
		}
	})
	.end()
	.find('.down').click(function(e){
		//alert(DoReader.currtype +'###'+DoReader.currpn);
		if (DoReader.currtype === 'v'){
			DoReader.go2next2();
		}else{
			DoReader.go2next();
		}
	})
	.end()
	.find('.currpn').mouseenter(function(){
		//if (DoReader.currtype === 'v'){
			$('#gotopage').fadeIn(600);
		//}	
	})
	.end()
	.find('.directory').mouseenter(function(){
		var dir = [];
		$h2 = DoReader.opt.container.find('.page-bd h2');
		if(!$h2.length){
			return false;
		}
		$h2.each(function(index){
			var inpn = $(this).parents('.page-item').attr('id').replace('item','');
			dir.push('<li><a rel="'+ inpn +'" href="#">'+$(this).text()+'...............'+inpn+'</a></li>');
		});
		$('#directory').html('<ul>'+dir.join('')+'</ul>').show();
	});
	
	$('#directory').delegate('a','click',function(e){
		e.preventDefault();
		var go2pn = $(this).attr('rel');
		if (DoReader.currtype === 'v'){
			DoReader.utils.go2page(go2pn);
		}else{
			DoReader.utils.go2page2(go2pn);
		}
	});
	$('#directory').mouseleave(function(){
		$(this).fadeOut(600);
	});
	$('#gotopage').mouseleave(function(){
		$('#gotopage').find('input[name=pnum]').focus();
		$('#gotopage').fadeOut(600);
	});
	$('#gotopage form').submit(function(e){
		e.preventDefault();
		var go2pn = $(this).find('input[name=pnum]').val();
		
		if(!/^[0-9]*[1-9][0-9]*$/.test(go2pn)){
			alert('format err');
			return false;
		}
		if(go2pn < 1 || go2pn > DoReader.pn){
			alert('range err');
			return false;
		}
		if (DoReader.currtype === 'v'){
			DoReader.utils.go2page(go2pn);
		}else{
			DoReader.utils.go2page2(go2pn);
		}
	});

};
//侧边栏事件
DoReader.showsidebar = function(){
	var zoomIn = function(){
			$('#zoomsetting').addClass('hover');
		},
		zoomOut = function(){
			$('#zoomsetting').removeClass('hover');
		},
		zoomTipsIn = function(){
			$('#zoomtips').addClass('hover');
		},
		zoomTipsOut = function(){
			$('#zoomtips').removeClass('hover');
		},
		shareIn = function(){
			$('#share').addClass('hover');
		},
		shareOut = function(){
			$('#share').removeClass('hover');
		},
		shareTipsIn = function(){
			$('#sharetips').addClass('hover');
		},
		shareTipsOut = function(){
			$('#sharetips').removeClass('hover');
		};
	$('#zoomsetting').mouseenter(zoomIn).mouseleave(zoomOut);
	$('#zoomtips').mouseenter(zoomTipsIn).mouseleave(zoomTipsOut);
	$('#share').mouseenter(shareIn).mouseleave(shareOut);
	$('#sharetips').mouseenter(shareTipsIn).mouseleave(shareTipsOut);
};
DoReader.showMyNotes = function(){
	var handleShowMynote = function(e){
		e.preventDefault();
		$('#overlay').css('height','1000px').show();
		var str = $('#db-templ-remarks').html();
		$('#myremarks').html(str).show();
		window.setInterval("DoReader.utils.autoIframe('ifaremarks')", 200);
		
		var _lantency = null,_layTime = 200;
		_lantency = setTimeout(function() {
			var overlayHeight = Math.max($('#myremarks').height(),$(document).height());
			var top = $(document).scrollTop();
			
			$('#overlay').css('height',(overlayHeight + top) + 'px');
			$('#myremarks').animate({
			  "top": (top > 0 ? top : 0)+'px'
			}, "slow");
		}, _layTime);
	},
	handleCloseMynote = function(e){
		e.preventDefault();
		$('#myremarks').hide();
		$('#overlay').hide();
	};
	$('#mynotes a').click(handleShowMynote);
	$('#myremarks').delegate('#closemynotes','click',handleCloseMynote);
};
DoReader.showSalon = function(){
	var handleShowSalon = function(e){
		e.preventDefault();
		$('#overlay').css('height','1000px').show();
		var str = $('#db-templ-salon').html();
		$('#salonbox').html(str).show();
		window.setInterval("DoReader.utils.autoIframe('ifasalon')", 200);
		
		var _lantency = null,_layTime = 200;
		_lantency = setTimeout(function() {
			var overlayHeight = Math.max($('#salonbox').height(),$(document).height());
			var top = $(document).scrollTop();
			
			$('#overlay').css('height',(overlayHeight + top) + 'px');
			$('#salonbox').animate({
			  "top": (top > 0 ? top : 0)+'px'
			}, "slow");
		}, _layTime);
	},
	handleCloseSalon = function(e){
		e.preventDefault();
		$('#salonbox').hide();
		$('#overlay').hide();
	};
	$('#salon a').click(handleShowSalon);
	$('#salonbox').delegate('#closesalon','click',handleCloseSalon);
};
//监听页码
DoReader.updateToolsPn = function(){
	$('#tools').find('.currpn').text(DoReader.currpn);
};
//批注事件
DoReader.showNotation = function(){
	//show remark
	DoReader.opt.container.find('.line').bind({
		mouseover : function(e){
			var oRemark = $(this).find('.remark-point:has(span)');
				oRemark.addClass('remark-active');
			if (oRemark.length && oRemark.position().left === 0) {
				oRemark.wrap('<div class="remark-wrap"></div>');
			}
		},
		mouseout : function(e){
			var oRemark = $(this).find('.remark-point:has(span)');
			
			oRemark.removeClass('remark-active');
			if (oRemark.parent('.remark-wrap').length) {
				oRemark.unwrap();
			}
		}
	});
	
	$('.remark-active').each(function() {
        var oRemark = $(this);
        if (oRemark.position().left === 0) {
            oRemark.wrap('<div class="remark-wrap"></div>');
        }
		oRemark.show();
    });

	// show remark content
	$('.remark-point').bind('click',function(e){
		e.stopPropagation();
		var sid = $(this).attr('data-sid');
		var line = $(this).attr('data-line');
		// var sid = 2,
		// line = 2;
		
		var id = $(this).parents('.page-item').attr('id'),
			oRemark = $(this);

		$(this).parents('.line').wrap('<div>');
		var domstr = $(this).parents('.line').parent().html();
		var notationform = '<div class="noteform mod"><form id="noteform" action="/nynote" method="post"><span class="close">关闭X</span><h2>添加批注</h2><div class="item"><textarea name="text"></textarea></div><input type="hidden" name="article_id" value="'+sid+'"><input type="hidden" name="line" value="'+line+'"><div class="btn"><input class="lnk-follow" type="submit" value="发表"></div><div class="error"></div></form></div><div id="viewall" class="viewall"><span><a id="noteshow" href="#">查看全部批注</a></span><span style="display:none"><a id="notehide" href="#">收起</a></span></div><div id="notebox" style="display:none"><div id="notesort" class="sort green_tab clearfix"><a class="on" href="#byhot"><span>按热度</span></a><a href="#bytime"><span>按时间</span></a></div><div class="notelist"><div class="list" id="notelist"></div><div id="notepage"></div></div></div>';

		var posY = $(this).parents('.line').offset().top;
		var posX = $(this).parents('.page-item').offset().left;

		var $elpage = $('#'+id);
		DoReader.opt.container.find('.line').removeClass('noted');
		
		$(this).parents('.line').addClass('noted');
		
		if($('#notation').length !== 0){
			$('#notation').html(domstr+notationform);
		}else{
			$('<div id="notation" class="notation">'+domstr+notationform+'</div>').appendTo('#container');
		}
		$notation = $('#notation');
		$notation.find('.remark-point').hide();
		$notation.css({'top': posY+'px','left':posX+'px'}).show();
		$notation.find('.line').css('margin-top',0);
		$notation.find('.close').click(function(e){
			$notation.hide();
		});
		$notation.data('line',line);
		$notation.data('sid',sid);
		
		//update p notes
		var updateNote = function(data){
			//note datas
			var allnote = data['paginator']['total'];
			var pernote = data['paginator']['perpage'];
			var pager = Math.ceil(allnote/pernote);
			var currpn = data['paginator']['start'];
			
			if(pager < 2){
				$('#notesort').hide();
			}

			//note items
			var temp = '<div class="listitem" id="noteid{$noteid}"><div class="con">{$con}</div> <div class="label">来自：<a href="{$url}">{$author}</a> <span class="pubdate">{$time}</span> <span class="act" style="{display}">| <a href="#edit" rel="{$noteid}">修改</a> <a href="#del" rel="{$noteid}">删除</a></span></div></div>';
	        var arr = [];
	        for(var i = 0 ; i < data['remarks'].length ; i++){
				var remarktext = DoReader.utils.escapeHTML(data['remarks'][i].text);
				var newtemp = DoReader.utils.tmpl(temp,{con:remarktext,author:data['remarks'][i].author.name,time:data['remarks'][i].time,noteid:data['remarks'][i].id,url:data['remarks'][i].author.url});

				if(data['remarks'][i].is_author){
					newtemp = newtemp.replace('{display}','');
				}else{
					newtemp = newtemp.replace('{display}','display:none');
				}
				arr.push(newtemp);
			}
			$('#notelist').html(arr.join(''));

			//note pagenav
			var pagenav = [];
			pagenav.push('<div class="paginator">');
			if(currpn === 0){
				pagenav.push('<span class="prev">&lt;前页</span>');
			}else{
				pagenav.push('<span class="prev"><a href="#" rel="'+ (currpn - 1) +'">&lt;前页</a></span>');
			}

			for(var i = 0 ; i < pager ; i++){
				if(i === currpn){
					pagenav.push('<span class="thispage">'+(i+1)+'</span>');
				}else{
					pagenav.push('<a href="#" rel="'+i+'">'+(i+1)+'</a>');
				}	
			}
			if(currpn === pager-1){
				pagenav.push('<span class="next">后页&gt;</span>');
			}else{
				pagenav.push('<span class="next"><a href="#" rel="'+ (currpn + 1) +'">后页&gt;</a></span>');
			}

			pagenav.push('<span class="count">(共'+ allnote +'个)</span></div>');

			$('#notepage').html(pagenav.join(''));
			
			//edit and del note
			$('#notelist a').bind('click',function(e){
				e.preventDefault();
				var noteid = $(this).attr('rel');
				var act = $(this).attr('href').replace('#','');
				var $noteitem = $(this).parents('#noteid'+noteid);
				if(act === 'del'){
					var isconfirm = confirm('你真的要删除该条信息？');
					if(isconfirm){
						$.ajax({  
						    type : 'GET',  
						    dataType : 'json',
						    url : '/j/remark/'+ noteid +'/remove?ck='+get_cookie('ck'),
						    success : function(data) {
								if(data.is_success){
									$noteitem.remove();
									var num = parseInt(oRemark.text(), 10) - 1;
									if (isNaN(num)) {
			                            oRemark.html('1<em></em>');
			                        } else {
			                            if(num === 0){
											oRemark.removeClass('remark-active');
											oRemark.html('<span></span><em></em>');
										}else{
											oRemark.html(num + '<em></em>');
										}
			                        }
								}
						    }		    
						});
					}
					
				}else{
					if(act === 'edit'){

						var str_form = '<div class="listitem"><form id="updateform" action="/j/remark/'+ noteid +'/update" method="post" class="noteform"><div class="item"><textarea name="text"></textarea></div><div class="btn"><input class="lnk-follow" type="submit" value="修改"></div><div class="error"></div></form></div>';
						$(str_form).insertAfter($noteitem);
						$noteitem.hide();
						$('#updateform').submit(function(e){
							var text_val = $("#updateform").find('textarea[name=text]').val();
							e.preventDefault();
							$.ajax({  
							    type : 'POST',  
							    dataType : 'json',
								data: $(this).serialize()+'&ck='+get_cookie('ck'),
							    url : $("#updateform").attr('action'),  
							    success : function(data) {
									if(data.is_success){
										$noteitem.find('.con').text(text_val);
										$noteitem.show();
										$('#updateform').parent().remove();
									}else{
										alert(data.error);
									}
							    }		    
							});
						});

					}
				}

			});

		};
		
		//get notes first
		$.ajax({  
		    type : 'GET',  
		    dataType : 'json',
		    url : '/j/remark/get_by_line?article_id='+sid+'&line='+line+'&start=0', 
		    success : function(data) {
		    	updateNote(data);
		    }		    
		});
		
		// sort note
		$notation.delegate('#notesort a','click',function(e){
			e.preventDefault();

			$('#notesort a').removeClass('on');
			$(this).addClass('on');
			var act = $(this).attr('href').replace('#','');
			//alert(act);
			$.ajax({  
			    type : 'GET',  
			    dataType : 'json',  
			    url : '/j/remark/get_by_line?article_id='+sid+'&line='+line+'&start=0',  
			    success : function(data) {
			    	updateNote(data);
			    }		    
			});

		});
		
		// to page
		$notation.delegate('.paginator a','click',function(e){
			e.preventDefault();

			var pn = $(this).attr('rel');
			$.ajax({  
			    type : 'GET',  
			    dataType : 'json',  
			    url : '/j/remark/get_by_line?article_id='+sid+'&line='+line+'&start='+pn,
			    success : function(data) {
			    	updateNote(data);
			    }		    
			});
		});
		
		//add note
		$('#noteform').bind('submit',function(e){
			e.preventDefault();

			$.ajax({  
			    type : 'POST',  
			    dataType : 'json',
				data: $(this).serialize()+'&ck='+get_cookie('ck'),
			    url : '/j/remark/add',  
			    success : function(data) {
					if(data.is_success){
						updateNote(data);
						console.log('add mark');
						$('#notebox').show();
						$('#noteshow').parent().hide();
						$('#notehide').parent().show();
						//oRemark.show();
						if(!oRemark.hasClass('remark-active')){
							oRemark.addClass('remark-active');
						}
						var num = parseInt(oRemark.text(), 10) + 1;
						if (isNaN(num)) {
                            oRemark.html('1<em></em>');
                        } else {
                            oRemark.html(num + '<em></em>');
                        }
						$('#noteform').find('textarea').val('');

					}else{
						alert(data.error);
					}
			    }		    
			});
		});
		
		// toogle notes
		$notation.delegate('#viewall a','click',function(e){
			e.preventDefault();
			var noteshow = function(){
				$('#noteshow').parent().hide();
				$('#notehide').parent().show();
				$('#notebox').show();
			},
			notehide = function(){
				$('#noteshow').parent().show();
				$('#notehide').parent().hide();
				$('#notebox').hide();
			};
			$(this).attr('id') === 'noteshow' ? noteshow() : notehide();
		});
		
	});
};
//关闭批注
DoReader.closeNotation = function(){
	$('#notation').hide();
};
//初始化脚注
DoReader.initSup = function(){
	//todo : show in right pos
	DoReader.opt.container.find('sup').mouseenter(function(e){
		e.preventDefault();
		var popinfo = $(this).attr('data-title'),
			offset = $(this).offset(),
			posTop = offset.top - 20,
			posLeft = offset.left + 20;

		$('#popinfo').text(popinfo).css({'position':'absolute','z-index':'10','left':posLeft +'px','top':posTop + 'px' }).show();
		
	}).mouseleave(function(){
		$('#popinfo').hide();
	});
};
//其他事件
DoReader.evt = {
	//键盘事件
	evtKey : function(e){
		if(/input|textarea/.test(e.target.tagName.toLowerCase())){
            return;
        }
        var c = (e.charCode) ? e.charCode : e.keyCode;
		if(DoReader.currtype === 'h') {
			switch (c){
				case 37: DoReader.go2prev();return false;//[<-]
				case 39: DoReader.go2next();return false;//[->]
				//case 38: go2prev();return false;//[^]
				//case 40: go2next();return false;//[V]
				case 75: DoReader.go2prev();return false;//[k]
				case 74: DoReader.go2next();return false;//[j]
				//default: alert(e.keyCode);
			}
		}else{
			switch (c){
				case 37: DoReader.go2prev2();return false;//[<-]
				case 39: DoReader.go2next2();return false;//[->]
				//case 38: go2prev();return false;//[^]
				//case 40: go2next();return false;//[V]
				case 75: DoReader.go2prev2();return false;//[k]
				case 74: DoReader.go2next2();return false;//[j]
				//default: alert(e.keyCode);
			}
		}
	},
	//版式缩放和底色事件
	evtZoom : function(){
		$('#zoomtips .ui-size').bind('click',function(e){
			var zoomstatus = $(this).data('zoom'),
				newzoom = zoomstatus === 'big'?'small':'big',
				ftsize = zoomstatus === 'big'?'16px':'14px';
			$('#container').css('font-size',ftsize);
			DoReader.currzoom = zoomstatus;
			$('#zoomtips .ui-size').removeClass('ui-size-on');
			$(this).addClass('ui-size-on');
			DoReader.updateTools();
			DoReader.closeNotation();
		});
		$('#zoomtips .ui-color').bind('click',function(e){
			var colorstatus = $(this).data('color'),
				style1 = {'color':'#000','background':'#fff'},
				style2 = {'color':'#ddd','background':'#333'},
				newstyle = colorstatus ==='style1'? style1 : style2;
				
			$('.page-item ').css(newstyle);
			$('#zoomtips .ui-color').removeClass('ui-color-on');
			$(this).addClass('ui-color-on');
		});
	},
	//window resize
	resize : function(){
		$(window).resize(function() {
			DoReader.updateTools();
		});
	},
	//阅读版式事件
	evtSwType : function(){
		$('#typesetting a').bind('click',function(e){
			e.preventDefault();

			var $readerbox = $('#readerbox'),
			$pageItem = $readerbox.find('.page-item'),
			$this = $(this),
			$setting = $('#typesetting'),
			render_h = function(){
				var readerbox = $('#readerbox');
				var pageLen = $pageItem.length;
				$pageItem.each(function(i){
					$(this).css('z-index',pageLen-i);
				});
				$readerbox.removeClass('vertical').addClass('horizontal');
				$pageItem.css('left','5em');
				DoReader.currtype = 'h';
				$this.attr('rel','v');
				$setting.removeClass('v').addClass('h');
				DoReader.updateTools();
			},
			render_v = function(){
				var readerbox = $('#readerbox');
				$readerbox.removeClass('horizontal').addClass('vertical');
				$pageItem.css({'z-index':1,'left':'0'});
				DoReader.currtype = 'v';
				$this.attr('rel','h');
				$setting.removeClass('h').addClass('v');
				DoReader.updateTools();
			},
			totype = $(this).attr('rel');
			
			DoReader.currpn = 1;
	        totype === 'h'?render_h() : render_v();
	        DoReader.closeNotation();
		});
	},
	//滚动事件
	evtScroll : function(){
		$(window).bind('scroll',function(e){
			//fix ie css fixed
			if(DoReader.currtype === 'v'){
				if($.browser.msie&&($.browser.version == "6.0")){
					$('#tools').hide();
					$('#sidebar').hide();
					//alert('ie');
				}
				var _lantency = null,_layTime = 200;
				_lantency = setTimeout(function() {
					var srcTop = $(window).scrollTop();
					var rdboxofftop = $('#readerbox').offset().top;
					var pagetop = parseInt(srcTop - rdboxofftop + 10);
					var $el_page = $('#readerbox .page-item').get(0);
					var perH = $($el_page).outerHeight(true);
					var _currpn = Math.floor(pagetop / perH);

					var top = $(window).scrollTop()+100;
										
					for(var i = 0 ; i < DoReader.pn ; i++){
						if (i == _currpn) {
							var idx = i+1;
					  		//window.location.hash = 'pn'+idx;
					  		DoReader.currpn = idx;
					  		DoReader.updateToolsPn();
						}
					}
					if($.browser.msie&&($.browser.version == "6.0")){
						$('#tools').css('top',top+'px').show();
						$('#sidebar').css({'top':$(window).scrollTop()+'px','position':'absolute'}).show();
					}
				}, _layTime);
			}
		});
	}
};
DoReader.init = function (){
	var cfg = {callback:function(){
		$(document).bind('keydown',DoReader.evt.evtKey);
		DoReader.initSup();
		$('#container').find('a[rel=lightbox]').lightBox();
		DoReader.showTools();
		DoReader.showsidebar();
		DoReader.showNotation();
		DoReader.showMyNotes();
		DoReader.showSalon();
		DoReader.evt.resize();
		// $("p").mousedown(function(){
		// 			//alert(this);
		// 			$(this).mouseout(function(){
		// 				alert('err');
		// 				return false;
		// 			})
		// 			.mouseup(function(){
		// 				alert(this);
		// 			    var selected = document.all ? this.ownerDocument.selection.createRange().text:this.ownerDocument.getSelection();  
		// 			    if(selected.toString().length > 0){
		// 					alert(selected.toString());
		// 				}   
		// 			});
		// 		});
	}};
	DoReader.render(cfg);
	DoReader.evt.evtScroll();
	DoReader.evt.evtZoom();
	DoReader.evt.evtSwType();

}
DoReader.preview = function (html){
	var cfg = {html:html};
	DoReader.render(cfg);
	DoReader.initSup();
}

